/******************************************************************************
 * Epigraph compiler                                                          *
 * Copyright © 2011 Grigorev Svyatoslav                                       *
 *                                                                            *
 * This program is free software: you can redistribute it and/or modify       *
 *     it under the terms of the GNU General Public License as published by   *
 *     the Free Software Foundation, either version 3 of the License, or      *
 *     (at your option) any later version.                                    *
 *                                                                            *
 *     This program is distributed in the hope that it will be useful,        *
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of         *
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the          *
 *     GNU General Public License for more details.                           *
 *                                                                            *
 *     You should have received a copy of the GNU General Public License      *
 *     along with this program.  If not, see <http://www.gnu.org/licenses/>.  *
 ******************************************************************************/

package org.gjt.sp.jedit.gui;


import org.gjt.sp.jedit.View;
import org.gjt.sp.jedit.jEdit;

import epg.Epigraph;
import org.gjt.sp.jedit.jEdit;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author: Grigorev Svyatoslav
 * Date: org.gjt.sp.jedit.gui 2011-08-29 16:27
 */

//{{{ Imports
import javax.swing.border.EmptyBorder;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.io.*;
import java.util.Random;

import org.gjt.sp.jedit.*;
import org.gjt.sp.util.Log;
//}}}

public class Compile extends EnhancedDialog {
	//{{{ TipOfTheDay constructor
	public Compile(View view) {
		super(view, jEdit.getProperty("compile.title"), false);

		JPanel content = new JPanel(new BorderLayout(12, 12));
		content.setBorder(new EmptyBorder(12, 12, 12, 12));
		setContentPane(content);

		JLabel label = new JLabel(jEdit.getProperty("compile.caption"));
		label.setFont(new Font("SansSerif", Font.PLAIN, 24));
		label.setForeground(UIManager.getColor("Button.foreground"));
		content.add(BorderLayout.NORTH, label);

		tipText = new JEditorPane();
		//tipText.setEditable(true);
		//tipText.setContentType("text/html");
		//tipText.setText();


		JScrollPane scroller = new JScrollPane(tipText);
		scroller.setPreferredSize(new Dimension(300, 300));
		content.add(BorderLayout.CENTER, scroller);

		ActionHandler actionHandler = new ActionHandler();

		Box buttons = new Box(BoxLayout.X_AXIS);


		debug = new JCheckBox("debug", true);
		debug.addActionListener(actionHandler);
		buttons.add(debug);


		buttons.add(Box.createHorizontalStrut(6));
		buttons.add(Box.createGlue());

		buttons.add(Box.createHorizontalStrut(6));

		run = new JButton(jEdit.getProperty("compile.run"));
		run.addActionListener(actionHandler);
		buttons.add(run);

		close = new JButton(jEdit.getProperty("common.close"));
		close.addActionListener(actionHandler);
		buttons.add(close);
		content.getRootPane().setDefaultButton(close);


		Dimension dim = run.getPreferredSize();
		dim.width = Math.max(dim.width, close.getPreferredSize().width);
		run.setPreferredSize(dim);
		close.setPreferredSize(dim);

		content.add(BorderLayout.SOUTH, buttons);

		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		pack();
		setLocationRelativeTo(view);
		setVisible(true);
	} //}}}

	//{{{ ok() method
	public void ok() {
		dispose();
	} //}}}

	//{{{ cancel() method
	public void cancel() {
		dispose();
	} //}}}

	//{{{ Private members

	//{{{ Instance variables
	private JButton close, run;
	private JEditorPane tipText;
	private int currentTip = -1;
	private JCheckBox debug;
	//}}}


	//}}}


	private void Run(String filename) throws Exception {
	//	tipText.setText(filename);
		/*tipText.setText("");
		Epigraph epg = new Epigraph(filename);
		if (debug.isSelected()) {
			tipText.setText(epg.getLog().toString());
		}*/
		String s;
		tipText.setText("");
		try {
			//tipText.setText("javac " + filename.substring(0, filename.lastIndexOf('.')) + ".java" );
			Process p = Runtime.getRuntime().exec("java -cp epigraph.jar;antlrworks-1.4.3.jar epg.Main \"" + filename + "\"");
		//	Process p = Runtime.getRuntime().exec("cmd.exe /C start java -cp D:\\sources\\epigraph\\trunk\\epigraph-compiler\\ TEST.Main");
			BufferedReader stdInput = new BufferedReader(new
				InputStreamReader(p.getInputStream()));

			BufferedReader stdError = new BufferedReader(new
				InputStreamReader(p.getErrorStream()));

			while ((s = stdError.readLine()) != null) {
				//System.out.println(s);
				tipText.setText(tipText.getText() + s + "\n");

			while ((s = stdInput.readLine()) != null) {
				if(debug.isSelected())
					tipText.setText(tipText.getText() + s + "\n");
			}
			}
		} catch (IOException e) {
			tipText.setText("exception happened - here's what I know: ");
			e.printStackTrace();
		}
	}

	private void doCompile(String filename) {
		String s;
		tipText.setText("");
		try {
			//tipText.setText("javac " + filename.substring(0, filename.lastIndexOf('.')) + ".java" );
			Process p = Runtime.getRuntime().exec("javac " + filename.substring(0, filename.lastIndexOf('.')) + ".java");

			BufferedReader stdInput = new BufferedReader(new
				InputStreamReader(p.getInputStream()));

			BufferedReader stdError = new BufferedReader(new
				InputStreamReader(p.getErrorStream()));

			while ((s = stdInput.readLine()) != null) {
				tipText.setText(tipText.getText() + s);
			}

			while ((s = stdError.readLine()) != null) {
				//System.out.println(s);
				tipText.setText(tipText.getText() + s);
			}
		} catch (IOException e) {
			tipText.setText("exception happened - here's what I know: ");
			e.printStackTrace();
		}
	}

	//{{{ ActionHandler class
	class ActionHandler implements ActionListener {
		public void actionPerformed(ActionEvent evt) {
			Object source = evt.getSource();
			if (source == close)
				dispose();
			else if (source == run) {
				Buffer buffer = jEdit.getActiveView().getBuffer();
				if (buffer.isUntitled()) {
					buffer.save(jEdit.getActiveView(), null);
				} else {
					run.setEnabled(false);
					buffer.save(jEdit.getActiveView(), buffer.getPath());
					try {
						Run(buffer.getPath());
					} catch (Exception e) {
						e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
					}
					//if (!nonCompile.isSelected()) doCompile(buffer.getPath());
					run.setEnabled(true);
				}
			}
		}
	} //}}}
}

